from django.shortcuts import render  # 导入Django的render函数，用于渲染模板
from .models import OrderItem,Order  # 从当前应用的models模块导入OrderItem和Order模型
from .forms import OrderCreateForm  # 从当前应用的forms模块导入OrderCreateForm表单
from cart.cart import Cart  # 从cart应用导入Cart类，用于处理购物车功能
from shop.models import Product  # 从shop应用导入Product模型，用于获取产品信息


def order_create(request):
    cart = Cart(request)  # 创建购物车实例
    if request.method == 'POST':  # 如果请求方法是POST
        form = OrderCreateForm(request.POST)  # 创建OrderCreateForm实例，并传入POST数据
        if form.is_valid():  # 如果表单数据有效
            order = form.save()  # 保存表单数据到数据库，并获取订单对象
            for item in cart:  # 遍历购物车中的每个商品
                a = Product.objects.get(name=item['product'])  # 获取商品对象
                if a.stock < item['quantity']:  # 如果库存不足
                    return render(request,  # 渲染失败页面
                                  'orders/order/faild.html',
                                  context={'stock':a.stock,
                                           'product':item['product'],
                                           'quantity':item['quantity']})
                a.stock -= item['quantity']  # 减少库存
                a.save()  # 保存商品对象
                OrderItem.objects.create(order=order,  # 创建订单项
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
            # clear the cart
            cart.clear()
            # launch asynchronous task
            # order_created.delay(order.id)
            return render(request, 'orders/order/created.html', {'order': order})
    else:
        form = OrderCreateForm()
    return render(request, 'orders/order/create.html', {'cart': cart,
                                                        'form': form})
def delete(request,order_id):
    order=Order.objects.get(id=order_id)
    order.delete()
    return render(request,'orders/order/delete_order.html',{'order_id':order_id})
def show(request):
    order = Order.objects.all()
    for i in order:
        i.total_cost = i.get_total_cost()
        i.save()
    return render(request,'orders/order/show_orders.html',{'orders':order})